#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include "dbg.h"

typedef int cybool;
#define true ((cybool)1)
#define false ((cybool)0)

int parserInt(const char *num);
cybool equal(const int x, const int y);

int main(int argc, char *argv[])
{
    char num[128];
    int ept, act;
    strcpy(num, "123");
    ept = 123;
    act = parserInt(num);
    check(equal(ept, act), "expct %d, but was %d", ept, act);
    
    strcpy(num, "123.1");
    ept = 123;
    act = parserInt(num);
    check(equal(ept, act), "expct %d, but was %d", ept, act);
    
    strcpy(num, "-123abc");
    ept = -123;
    act = parserInt(num);
    check(equal(ept, act), "expct %d, but was %d", ept, act);
    
    // error test
    strcpy(num, "1abc11");
    ept = 1;
    act = parserInt(num);
    check(equal(ept, act), "expct %d, but was %d", ept, act);
    
    strcpy(num, "-a1");
    ept = 0;
    act = parserInt(num);
    check(equal(ept, act), "expct %d, but was %d", ept, act);
    
    return 0;

error:
    return 1;
}

cybool equal(const int x, const int y)
{
    return x == y ? true : false;
}

int parserInt(const char *num)
{
    //int c;	// current char
    int i = 0;
    int n = 0;	// result
    int sign;   // if '-', then negative, otherwise positive

    // skip whitespace
    while(isspace(num[i]))
        i++;

    if(num[i] == '-' || num[i] == '+') {
        sign = num[i];
        i++;
    }
    else {
        sign = '+';
    }

    while(isdigit(num[i])) {
        n = 10 * n + (num[i] - '0');
        i++;
    }

    if(sign == '-')
        return -n;
    else
        return n;
}

